﻿namespace WebPacker.Filters
{
	using System;
	using WebPacker.Packs;

	public class CompositeFilter : IFilter
	{
		private IFilter[] filters;

		public CompositeFilter()
		{
			PackType = PackType.JavaScript;
		}

		public string Name { get; set; }

		public PackType PackType { get; set; }

		public IFilter[] Filters
		{
			get
			{
				return filters;
			}

			set
			{
				if (value != null)
				{
					foreach (var item in value)
					{
						if (item.PackType != PackType)
						{
							throw new ArgumentException(string.Format("Unsupported type of filter \"{0}\"", item.Name));
						}
					}
				}

				filters = value;
			}
		}

		public string Apply(string content)
		{
			if (content == null)
			{
				throw new ArgumentNullException("content");
			}

			if (Filters != null)
			{
				foreach (var filter in filters)
				{
					content = filter.Apply(content);
				}
			}

			return content;
		}

		public string ApplyToCombined(string combinedContent)
		{
			if (combinedContent == null)
			{
				throw new ArgumentNullException("combinedContent");
			}		

			if (Filters != null)
			{
				foreach (var filter in filters)
				{
					combinedContent = filter.ApplyToCombined(combinedContent);
				}
			}

			return combinedContent;
		}
	}
}